package fr.sunnydale.android.geek.sprite.impl;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import fr.sunnydale.android.geek.entity.impl.AbstractTiledEntity;
import fr.sunnydale.android.geek.sprite.IFrameDef;
import fr.sunnydale.android.geek.sprite.ISprite;
import fr.sunnydale.android.geek.thread.TimerThread;
import fr.sunnydale.android.geek.util.GUtils;
import fr.sunnydale.android.geek.util.Speed;

public abstract class Sprite extends AbstractTiledEntity implements ISprite {

    public Bitmap mSprite;
    public Speed mSpeed;
    private int mCurrentFrame;
    private Rect mFrameCoord = new Rect(0, 0, Float.valueOf(GUtils.TILESIZE).intValue(), Float.valueOf(GUtils.TILESIZE)
            .intValue());
    protected IFrameDef mFrameDef = FrameDef.DEFAULT;

    public static class FrameDef implements IFrameDef {

        private int startFrame;
        private int endFrame;
        public static IFrameDef DEFAULT = new FrameDef(0, 1);

        protected FrameDef() {
            this.startFrame = 0;
            this.endFrame = 0;
        }

        protected FrameDef(int startFrame, int endFrame) {
            this.startFrame = startFrame;
            this.endFrame = endFrame;
        }

        @Override
        public int getLast() {
            return endFrame;
        }

        @Override
        public int getStart() {
            return startFrame;
        }
    }

    public void init(Bitmap sprite, TimerThread clock, Speed speed) {
        mSprite = sprite;
        mSpeed = speed;
        mCurrentFrame = 0;
        clock.attach(speed, this.hashCode());
    }

    @Override
    public synchronized void draw(Canvas canvas, TimerThread clock) {
        if (clock.hasToRefresh(this.hashCode())) {
            mCurrentFrame++;
            mFrameCoord.offset(Float.valueOf(GUtils.TILESIZE).intValue(), 0);
            if (mCurrentFrame > mFrameDef.getLast()) {
                mCurrentFrame = mFrameDef.getStart();
                mFrameCoord.set(GUtils.getScaledRect(mFrameDef.getStart() * 50, 0, 50 + mFrameDef.getStart() * 50, 50));
            }
        }
        canvas.drawBitmap(mSprite, mFrameCoord, GUtils.getScaledRect(new Rect(mCoord.x * 50, mCoord.y * 50,
                50 + mCoord.x * 50, 50 + mCoord.y * 50)), null);
    }

    @Override
    public abstract void touchAction();
}
